const base = require("./../base");
const moment = require("moment");

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
        await super.isShopAuth();
        await super.isUserAuth();
    }

    /**
     *
     * @api {get} /shop/api/shop/collection/index 收藏列表
     * @apiDescription 收藏列表
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} page   页码
     *
     * @apiSampleRequest /shop/api/shop/collection/index
     *
     */
    async index() {
        const { page = 1, type = "shop_product" } = this.query;
        const shopId = this.state.shop.id;
        const userId = this.state.user.id;

        const collection = await this.model("user_collection")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("user_id", userId);
                qb.where("collection_type", type);
            })
            .fetchPage({ pageSize: 20, page: page, withRelated: ["product"] });
        this.success(collection);
    }

    /**
     *
     * @api {get} /shop/api/shop/collection/add 添加收藏
     * @apiDescription 添加收藏
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} id   商品id
     *
     * @apiSampleRequest /shop/api/shop/collection/add
     *
     */
    async add() {
        const { id, type = "shop_product" } = this.query;
        const shopId = this.state.shop.id;
        const userId = this.state.user.id;

        const collection = await this.model("user_collection")
            .forge({
                shop_id: shopId,
                user_id: userId,
                collection_id: id,
                collection_type: type
            })
            .save();
        this.success(collection);
    }

    /**
     *
     * @api {get} /shop/api/shop/collection/del 删除收藏
     * @apiDescription 删除收藏
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {Number} id   收藏id
     *
     * @apiSampleRequest /shop/api/shop/collection/del
     *
     */
    async del() {
        const { id } = this.query;
        const shopId = this.state.shop.id;
        const userId = this.state.user.id;

        const collection = await this.model("user_collection")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("user_id", userId);
                qb.where("id", id);
            })
            .destroy();
        this.success(collection);
    }
};
